package com.study.second_kill.server.controller;

import com.study.second_kill.model.entity.ItemKill;
import com.study.second_kill.server.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @Author xiongmin
 * @Description //TODO
 * @Date 2020/4/19 17:58
 * @Version 1.0
 **/
@Controller
@Slf4j
public class ItemController {

    private static final String prefix="item";

    @Autowired
    IItemService itemService;

    /**
     * 获取代秒杀商品列表
     * @param modelMap
     * @return
     */
    @RequestMapping(value = {"/","/index",prefix+"/list",prefix+"/index.html"})
    public String list(ModelMap modelMap) {
        try {
            List<ItemKill> killItems = itemService.getKillItems();
            modelMap.addAttribute("list",killItems);
            log.info("获取带秒杀商品列表数据，{}",killItems);
        } catch (Exception e) {
            log.error("获取带秒杀商品列表数据, 发生异常：{}",e.getMessage());
            return "redirect:/base/error";
        }
        return "list";
    }


    /**
     * 获取代秒杀商品详情
     * @param id
     * @return
     */
    @GetMapping(value = {prefix+"/detail/{id}"})
    public String detail(@PathVariable("id")Integer id,ModelMap modelMap) {
        if (id == null || id < 1) {
            return "redirect:/base/error";
        }
        try {
            ItemKill detail = itemService.getKillDetail(id);
            modelMap.addAttribute("detail",detail);
        } catch (Exception e) {
            log.error("获取代秒杀商品详情失败，id = {}",id,e.fillInStackTrace());
            return "redirect:/base/error";
        }
        return "info";
    }

}
